#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
作业管理API路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
import json
from models import db, User, Class, Assignment, AssignmentSubmission, Problem
from decorators import teacher_required, student_required

assignments_bp = Blueprint('assignments', __name__)

@assignments_bp.route('/', methods=['GET'])
@jwt_required()
def get_assignments():
    """获取作业列表"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        if current_user.role == 'admin':
            # 管理员可以看到所有作业
            assignments = Assignment.query.order_by(Assignment.created_at.desc()).all()
        elif current_user.role == 'teacher':
            # 教师只能看到自己班级的作业
            teacher_classes = Class.query.filter_by(teacher_id=current_user_id).all()
            class_ids = [cls.id for cls in teacher_classes]
            assignments = Assignment.query.filter(Assignment.class_id.in_(class_ids)).order_by(Assignment.created_at.desc()).all()
        else:
            # 学生只能看到自己班级的作业
            student_classes = current_user.enrolled_classes
            class_ids = [cls.id for cls in student_classes]
            assignments = Assignment.query.filter(Assignment.class_id.in_(class_ids)).order_by(Assignment.created_at.desc()).all()
        
        return jsonify({
            'code': 200,
            'message': '获取作业列表成功',
            'data': [assignment.to_dict() for assignment in assignments]
        })
        
    except Exception as e:
        return jsonify({'error': f'获取作业列表失败: {str(e)}'}), 500

@assignments_bp.route('/<int:assignment_id>', methods=['GET'])
@jwt_required()
def get_assignment_detail(assignment_id):
    """获取作业详情"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        assignment = Assignment.query.get(assignment_id)
        if not assignment:
            return jsonify({'error': '作业不存在'}), 404
        
        # 检查权限
        if current_user.role == 'student':
            if assignment.class_obj not in current_user.enrolled_classes:
                return jsonify({'error': '无权访问此作业'}), 403
        elif current_user.role == 'teacher':
            if assignment.class_obj.teacher_id != current_user_id:
                return jsonify({'error': '无权访问此作业'}), 403
        
        # 获取关联的题目信息
        problem_ids = json.loads(assignment.problem_ids) if assignment.problem_ids else []
        problems = Problem.query.filter(Problem.id.in_(problem_ids)).all()
        
        assignment_data = assignment.to_dict()
        assignment_data['problems'] = [problem.to_dict() for problem in problems]
        
        return jsonify({
            'code': 200,
            'message': '获取作业详情成功',
            'data': assignment_data
        })
        
    except Exception as e:
        return jsonify({'error': f'获取作业详情失败: {str(e)}'}), 500

@assignments_bp.route('/', methods=['POST'])
@teacher_required
def create_assignment():
    """创建作业"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('title'):
            return jsonify({'error': '作业标题不能为空'}), 400
        
        if not data.get('class_id'):
            return jsonify({'error': '班级ID不能为空'}), 400
        
        if not data.get('due_date'):
            return jsonify({'error': '截止时间不能为空'}), 400
        
        # 检查班级权限
        class_obj = Class.query.get(data['class_id'])
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        if class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权在此班级创建作业'}), 403
        
        # 验证题目ID
        problem_ids = data.get('problem_ids', [])
        if problem_ids:
            problems = Problem.query.filter(Problem.id.in_(problem_ids)).all()
            if len(problems) != len(problem_ids):
                return jsonify({'error': '部分题目不存在'}), 400
        
        # 创建作业
        new_assignment = Assignment(
            title=data['title'],
            description=data.get('description', ''),
            class_id=data['class_id'],
            problem_ids=json.dumps(problem_ids),
            due_date=datetime.fromisoformat(data['due_date'].replace('Z', '+00:00')),
            total_score=data.get('total_score', 100.0),
            status='active'
        )
        
        db.session.add(new_assignment)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建作业成功',
            'data': new_assignment.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建作业失败: {str(e)}'}), 500

@assignments_bp.route('/<int:assignment_id>', methods=['PUT'])
@teacher_required
def update_assignment(assignment_id):
    """更新作业"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        assignment = Assignment.query.get(assignment_id)
        if not assignment:
            return jsonify({'error': '作业不存在'}), 404
        
        # 检查权限
        if assignment.class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权修改此作业'}), 403
        
        # 更新字段
        if 'title' in data:
            assignment.title = data['title']
        
        if 'description' in data:
            assignment.description = data['description']
        
        if 'problem_ids' in data:
            # 验证题目ID
            problem_ids = data['problem_ids']
            if problem_ids:
                problems = Problem.query.filter(Problem.id.in_(problem_ids)).all()
                if len(problems) != len(problem_ids):
                    return jsonify({'error': '部分题目不存在'}), 400
            assignment.problem_ids = json.dumps(problem_ids)
        
        if 'due_date' in data:
            assignment.due_date = datetime.fromisoformat(data['due_date'].replace('Z', '+00:00'))
        
        if 'total_score' in data:
            assignment.total_score = data['total_score']
        
        if 'status' in data:
            assignment.status = data['status']
        
        assignment.updated_at = datetime.utcnow()
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新作业成功',
            'data': assignment.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新作业失败: {str(e)}'}), 500

@assignments_bp.route('/<int:assignment_id>/submissions', methods=['POST'])
@student_required
def submit_assignment(assignment_id):
    """提交作业"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        assignment = Assignment.query.get(assignment_id)
        if not assignment:
            return jsonify({'error': '作业不存在'}), 404
        
        # 检查学生是否在作业班级中
        if assignment.class_obj not in current_user.enrolled_classes:
            return jsonify({'error': '无权提交此作业'}), 403
        
        # 检查作业是否已过期
        if assignment.is_expired():
            return jsonify({'error': '作业已过期，无法提交'}), 400
        
        problem_id = data.get('problem_id')
        if not problem_id:
            return jsonify({'error': '题目ID不能为空'}), 400
        
        # 检查题目是否在作业中
        problem_ids = json.loads(assignment.problem_ids) if assignment.problem_ids else []
        if problem_id not in problem_ids:
            return jsonify({'error': '题目不在作业中'}), 400
        
        # 检查是否已提交过
        existing_submission = AssignmentSubmission.query.filter_by(
            assignment_id=assignment_id,
            student_id=current_user_id,
            problem_id=problem_id
        ).first()
        
        if existing_submission:
            return jsonify({'error': '已提交过此题目'}), 400
        
        # 创建提交记录
        submission = AssignmentSubmission(
            assignment_id=assignment_id,
            student_id=current_user_id,
            problem_id=problem_id,
            code=data.get('code', ''),
            language=data.get('language', 'python'),
            status='pending'
        )
        
        db.session.add(submission)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '提交作业成功',
            'data': submission.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'提交作业失败: {str(e)}'}), 500

@assignments_bp.route('/<int:assignment_id>/submissions', methods=['GET'])
@jwt_required()
def get_assignment_submissions(assignment_id):
    """获取作业提交记录"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        assignment = Assignment.query.get(assignment_id)
        if not assignment:
            return jsonify({'error': '作业不存在'}), 404
        
        # 检查权限
        if current_user.role == 'student':
            if assignment.class_obj not in current_user.enrolled_classes:
                return jsonify({'error': '无权访问此作业'}), 403
            # 学生只能看到自己的提交
            submissions = AssignmentSubmission.query.filter_by(
                assignment_id=assignment_id,
                student_id=current_user_id
            ).all()
        else:
            # 教师可以看到所有学生的提交
            if assignment.class_obj.teacher_id != current_user_id:
                return jsonify({'error': '无权访问此作业'}), 403
            submissions = AssignmentSubmission.query.filter_by(assignment_id=assignment_id).all()
        
        return jsonify({
            'code': 200,
            'message': '获取提交记录成功',
            'data': [submission.to_dict() for submission in submissions]
        })
        
    except Exception as e:
        return jsonify({'error': f'获取提交记录失败: {str(e)}'}), 500

@assignments_bp.route('/submissions/<int:submission_id>/grade', methods=['POST'])
@teacher_required
def grade_submission(submission_id):
    """批改作业提交"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        submission = AssignmentSubmission.query.get(submission_id)
        if not submission:
            return jsonify({'error': '提交记录不存在'}), 404
        
        # 检查权限
        if submission.assignment.class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权批改此提交'}), 403
        
        # 更新批改信息
        submission.score = data.get('score', 0.0)
        submission.feedback = data.get('feedback', '')
        submission.graded_at = datetime.utcnow()
        submission.graded_by = current_user_id
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '批改成功',
            'data': submission.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'批改失败: {str(e)}'}), 500

@assignments_bp.route('/<int:assignment_id>/stats', methods=['GET'])
@teacher_required
def get_assignment_stats(assignment_id):
    """获取作业统计信息"""
    try:
        current_user_id = int(get_jwt_identity())
        
        assignment = Assignment.query.get(assignment_id)
        if not assignment:
            return jsonify({'error': '作业不存在'}), 404
        
        # 检查权限
        if assignment.class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权访问此作业'}), 403
        
        # 获取统计信息
        stats = assignment.get_submission_stats()
        
        # 获取题目统计
        problem_ids = json.loads(assignment.problem_ids) if assignment.problem_ids else []
        problem_stats = []
        
        for problem_id in problem_ids:
            problem = Problem.query.get(problem_id)
            if problem:
                submissions = AssignmentSubmission.query.filter_by(
                    assignment_id=assignment_id,
                    problem_id=problem_id
                ).all()
                
                problem_stat = {
                    'problem_id': problem_id,
                    'problem_title': problem.title,
                    'total_submissions': len(submissions),
                    'accepted_count': len([s for s in submissions if s.status == 'accepted']),
                    'average_score': sum(s.score for s in submissions) / len(submissions) if submissions else 0
                }
                problem_stats.append(problem_stat)
        
        stats['problem_stats'] = problem_stats
        
        return jsonify({
            'code': 200,
            'message': '获取作业统计成功',
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'error': f'获取作业统计失败: {str(e)}'}), 500
